<template>
  <div class="p-4">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="font-semibold text-lg">用户留言管理</h3>
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            <span>刷新</span>
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选区域 -->
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="留言内容">
          <el-input v-model="searchForm.content" placeholder="请输入留言内容" clearable />
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="留言状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option v-for="(item, key) in statusMap" :key="key" :label="item" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="留言时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 留言列表 -->
      <el-table
        :data="messageList"
        stripe
        border
        fit
        highlight-current-row
        @row-click="handleViewDetail"
        style="cursor: pointer;"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名称" width="120"></el-table-column>
        <el-table-column prop="content" label="留言内容" min-width="200">
          <template #default="scope">
            <span class="line-clamp-2">{{ scope.row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ statusMap[scope.row.status] || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="留言时间" width="180"></el-table-column>
        <el-table-column prop="replyTime" label="回复时间" width="180">
          <template #default="scope">
            <span>{{ scope.row.replyTime || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleViewDetail(scope.row, $event)"
            >
              查看
            </el-button>
            <el-button 
              size="small" 
              v-if="scope.row.status === 'pending'"
              type="success" 
              @click="handleReply(scope.row, $event)"
            >
              回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-4 flex justify-center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 留言详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      :title="`${currentMessage.id ? '留言详情' : '新留言'}`" 
      :width="600"
    >
      <template #content>
        <el-card class="mb-4">
          <template #header>
            <span>留言信息</span>
          </template>
          <div class="space-y-4">
            <div>
              <p class="text-sm text-gray-500 mb-1">用户名称</p>
              <p>{{ currentMessage.username }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">联系电话</p>
              <p>{{ currentMessage.phone || '-' }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">电子邮箱</p>
              <p>{{ currentMessage.email || '-' }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">留言时间</p>
              <p>{{ currentMessage.createTime }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">留言内容</p>
              <p class="whitespace-pre-line p-3 bg-gray-50 rounded">{{ currentMessage.content }}</p>
            </div>
          </div>
        </el-card>

        <el-card v-if="currentMessage.status === 'replied'">
          <template #header>
            <span>回复信息</span>
          </template>
          <div class="space-y-4">
            <div>
              <p class="text-sm text-gray-500 mb-1">回复人</p>
              <p>{{ currentMessage.replyOperator || '系统管理员' }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">回复时间</p>
              <p>{{ currentMessage.replyTime }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">回复内容</p>
              <p class="whitespace-pre-line p-3 bg-gray-50 rounded">{{ currentMessage.replyContent }}</p>
            </div>
          </div>
        </el-card>
      </template>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button 
          v-if="currentMessage.status === 'pending'"
          type="success" 
          @click="handleReply(currentMessage)"
        >
          回复
        </el-button>
      </template>
    </el-dialog>

    <!-- 回复对话框 -->
    <el-dialog v-model="replyVisible" title="回复留言" :width="600">
      <template #content>
        <el-form
          ref="replyFormRef"
          :model="replyForm"
          :rules="replyRules"
          label-width="80px"
        >
          <el-form-item label="留言内容" disabled>
            <el-input 
              v-model="replyForm.originalContent" 
              type="textarea" 
              rows="3"
              disabled
            />
          </el-form-item>
          <el-form-item label="回复内容" prop="replyContent">
            <el-input 
              v-model="replyForm.replyContent" 
              type="textarea" 
              rows="5"
              placeholder="请输入回复内容"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="replyVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReply">提交回复</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

// 状态映射
const statusMap = {
  pending: '未处理',
  replied: '已回复',
  closed: '已关闭'
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'replied':
      return 'success'
    case 'closed':
      return 'info'
    default:
      return 'info'
  }
}

// 模拟留言数据
const mockMessages = [
  {
    id: 1,
    username: '张三',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    content: '请问这个商品支持7天无理由退货吗？如果有质量问题可以退换货吗？',
    status: 'replied',
    createTime: '2023-09-01 10:30:00',
    replyTime: '2023-09-01 11:45:00',
    replyContent: '您好，我们的商品支持7天无理由退货，质量问题15天内可以凭质检报告退换货。',
    replyOperator: '客服小美'
  },
  {
    id: 2,
    username: '李四',
    phone: '',
    email: 'lisi@example.com',
    content: '订单已经付款了，什么时候可以发货？',
    status: 'replied',
    createTime: '2023-09-02 14:15:00',
    replyTime: '2023-09-02 15:30:00',
    replyContent: '您好，当天16点前付款的订单会在当天发货，您的订单会在今天发出。',
    replyOperator: '客服小丽'
  },
  {
    id: 3,
    username: '王五',
    phone: '13700137003',
    email: '',
    content: '收到的商品和描述不符，想申请退货',
    status: 'pending',
    createTime: '2023-09-03 09:45:00',
    replyTime: null,
    replyContent: null,
    replyOperator: null
  },
  {
    id: 4,
    username: '赵六',
    phone: '13600136004',
    email: 'zhaoliu@example.com',
    content: '请问有优惠活动吗？想买多个产品',
    status: 'pending',
    createTime: '2023-09-04 16:20:00',
    replyTime: null,
    replyContent: null,
    replyOperator: null
  },
  {
    id: 5,
    username: '钱七',
    phone: '13500135005',
    email: 'qianqi@example.com',
    content: '产品使用过程中出现了故障，如何申请售后？',
    status: 'closed',
    createTime: '2023-09-05 11:30:00',
    replyTime: '2023-09-05 13:20:00',
    replyContent: '您好，请在APP内找到"我的订单"，选择对应订单点击"申请售后"即可。',
    replyOperator: '客服小张'
  }
]

// 状态管理
const messageList = ref([])
const detailVisible = ref(false)
const replyVisible = ref(false)
const currentMessage = ref({})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const localMessages = ref([...mockMessages])

// 搜索表单
const searchForm = reactive({
  content: '',
  username: '',
  status: '',
  dateRange: []
})

// 回复表单
const replyForm = reactive({
  id: null,
  originalContent: '',
  replyContent: ''
})

// 回复表单验证规则
const replyRules = reactive({
  replyContent: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { max: 500, message: '回复内容不能超过500个字符', trigger: 'blur' }
  ]
})

// 表单引用
const replyFormRef = ref(null)

// 获取留言列表
const fetchMessageList = () => {
  // 应用搜索筛选
  let filtered = [...localMessages.value]
  
  if (searchForm.content) {
    filtered = filtered.filter(item => 
      item.content.includes(searchForm.content)
    )
  }
  
  if (searchForm.username) {
    filtered = filtered.filter(item => 
      item.username.includes(searchForm.username)
    )
  }
  
  if (searchForm.status) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange
    filtered = filtered.filter(item => {
      const messageDate = new Date(item.createTime).getTime()
      const start = new Date(startDate).getTime()
      const end = new Date(endDate).getTime() + 24 * 60 * 60 * 1000 // 包含结束日期当天
      
      return messageDate >= start && messageDate <= end
    })
  }
  
  // 模拟分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  messageList.value = filtered.slice(start, end)
  total.value = filtered.length
}

// 搜索留言
const handleSearch = () => {
  currentPage.value = 1
  fetchMessageList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.content = ''
  searchForm.username = ''
  searchForm.status = ''
  searchForm.dateRange = []
  currentPage.value = 1
  fetchMessageList()
}

// 刷新列表
const handleRefresh = () => {
  fetchMessageList()
  ElMessage.success('刷新成功')
}

// 查看详情
const handleViewDetail = (row, event) => {
  if (event) {
    event.stopPropagation() // 阻止行点击事件冒泡
  }
  
  currentMessage.value = JSON.parse(JSON.stringify(row))
  detailVisible.value = true
}

// 回复留言
const handleReply = (row, event) => {
  if (event) {
    event.stopPropagation() // 阻止行点击事件冒泡
  }
  
  // 关闭详情对话框
  detailVisible.value = false
  
  // 填充回复表单
  replyForm.id = row.id
  replyForm.originalContent = row.content
  replyForm.replyContent = ''
  
  // 显示回复对话框
  nextTick(() => {
    replyVisible.value = true
  })
}

// 提交回复
const submitReply = () => {
  replyFormRef.value?.validate(valid => {
    if (!valid) return false
    
    // 查找并更新留言
    const index = localMessages.value.findIndex(item => item.id === replyForm.id)
    if (index !== -1) {
      localMessages.value[index] = {
        ...localMessages.value[index],
        status: 'replied',
        replyTime: new Date().toLocaleString(),
        replyContent: replyForm.replyContent,
        replyOperator: '当前管理员'
      }
      
      ElMessage.success('回复成功')
      replyVisible.value = false
      fetchMessageList()
    } else {
      ElMessage.error('留言不存在')
    }
  })
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchMessageList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchMessageList()
}

// 生命周期钩子
onMounted(() => {
  fetchMessageList()
})
</script>

<style scoped>
/* 自定义样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>